import React, { useState, useEffect } from 'react';
import { SearchOutlined } from "@ant-design/icons";
import { getFindByParentId } from '@/api/dict';
import { getHospitalLList, getUpdateStatus } from '@/api/hosp'
import { useNavigate } from 'react-router-dom';
import { Button, Form, Input, Select, Space, Switch, Table } from "antd";
const { Option } = Select;


function HospitalList() {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false);

  // 医院状态列表
  const [hospitalList, setHospitalList] = useState([]);
  // 医院页码
  const [pageInfo, setPageInfo] = useState({
    // current: 1,
    // 页码存在localStorage
    current: localStorage.getItem("current") ? parseInt(localStorage.getItem("current") as string) : 1,
    pageSize: 5,
    total: 10
  })


  // 发请求
  const getHospitalListAsync:any = async (current: number, pageSize: number) => {
    setLoading(true)
    // 请求列表  form.getFieldsValue 获取表单内容
    const result = await getHospitalLList(current, pageSize,form.getFieldsValue())
    localStorage.setItem("current", result.data.number + 1); // 读取localStorage
    // 请求成功更改状态
    setPageInfo({
      pageSize: result.data.size,
      current: result.data.number + 1,
      total: result.data.totalElements
    })
    setHospitalList(result.data.content);
    setLoading(false)
  }


  // 定义医院类型列表
  const [hostypeList, setHostypeList] = useState([]);
  // 定义省份列表
  const [provinceCodeList, setProvinceCodeList] = useState([])
  // 定义城市列表
  const [cityCodeList, setCityCodeList] = useState([])
  // 定义区列表
  const [districtCodeList, setDistrictCodeList] = useState([]);

  useEffect(() => {
    // 调用医院列表
    getHospitalListAsync(pageInfo.current, pageInfo.pageSize)
    // 找到医院类型 医院等级
    getFindByParentId(10000).then(value => {
      // console.log(value);
      setHostypeList(value.data)
    })
    // 找到省份列表
    getFindByParentId(86).then(value => {
      // console.log(value)
      setProvinceCodeList(value.data);
    })
  }, [])
  const [form] = Form.useForm(); // form实例化
  return (
    <div>

      <Space style={{ marginBottom: 16 }}>
        {/* 搜索功能 表单 */}
        <Form
          form={form}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={(values: any) => {
            console.log(values);
            console.log(pageInfo.pageSize);  // 当前数据个数
            getHospitalListAsync(1, pageInfo.pageSize)
          }}
          autoComplete="off"
          layout={"inline"}
        >


          {/* 选择省份 name属性和匹配 */}
          <Form.Item name={"provinceCode"}>
            <Select onChange={async (value) => {
              const result = await getFindByParentId(value); // 发起网络请求
              // console.log(result);
              form.setFieldsValue({ // 清空输入框
                cityCode: undefined,
                districtCode: undefined
              })
              setCityCodeList(result.data); // 填入请求来的数据
              setDistrictCodeList([])
            }} placeholder={"请选择省份"}>
              {
                provinceCodeList.map((item: any) => (
                  <Option key={item.id} value={item.value}>{item.name}</Option>
                ))
              }
            </Select>
          </Form.Item>
          {/* 选择城市 */}
          <Form.Item name={"cityCode"}>
            <Select onChange={async value => {
              const result = await getFindByParentId(value);
              // console.log(result);
              form.setFieldsValue({
                districtCode: undefined
              })
              setDistrictCodeList(result.data);
            }} placeholder={"请选择城市"}>
              {
                cityCodeList.map((item: any) => (
                  <Option key={item.id} value={item.value}>{item.name}</Option>
                ))
              }
            </Select>
          </Form.Item>

          {/* 选择城区 */}
          <Form.Item name={"districtCode"}>
            <Select placeholder={"请选择区"}>
              {
                districtCodeList.map((item: any) => (
                  <Option key={item.id} value={item.value}>{item.name}</Option>
                ))
              }
            </Select>
          </Form.Item>


          <Form.Item name={"hostype"}>
            <Select placeholder={"请选择医院类型"}>
              {
                hostypeList.map((item: any) => (
                  <Option key={item.id} value={item.value}>{item.name}</Option>
                ))
              }
            </Select>
          </Form.Item>



          <Form.Item
            name="hosname" // name属性要改成hosname
          >
            <Input placeholder={"请输入医院名称"} />
          </Form.Item>
          <Form.Item
            name="hoscode"
          >
            <Input placeholder={"请输入医院编码"} />
          </Form.Item>
          <Form.Item>
            <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={() => {
              form.resetFields();// 重置表单
              getHospitalListAsync(1, pageInfo.pageSize);
            }} htmlType="button">
              重置
            </Button>
          </Form.Item>
        </Form>

      </Space>






      <Table
        loading={loading}
        bordered={true}
        rowKey={"id"}
        pagination={{
          ...pageInfo,
          // onChange(current,pageSize){
          //     getHospitalListAsync(current,pageSize);
          // }
          onChange: getHospitalListAsync
        }}
        columns={[
          {
            title: "序号",
            align: "center",
            render(value, rows, index) {
              return (pageInfo.current - 1) * pageInfo.pageSize + index + 1;
            }
          }, {
            title: "医院名称",
            align: "center",
            dataIndex: "hosname"
          }, {
            title: "医院编码",
            align: "center",
            dataIndex: "hoscode"
          }, {
            title: "医院LOGO",
            align: "center",
            dataIndex: "logoData",
            render(logoData) {
              return (
                <img width={50} src={"data:image/png;base64," + logoData} alt="" />
              )
            }
          }, {
            title: "是否上线",
            align: "center",
            // dataIndex: "status", // 这行注释  render的参数才是行信息
            // 0：未上线 1：已上线
            render(rows) {
              return (
                <Switch checked={rows.status === 1}
                  onChange={async () => {
                    console.log(rows.id);
                    await getUpdateStatus(rows.id, rows.status === 1 ? 0 : 1)
                    await getHospitalListAsync(pageInfo.current, pageInfo.pageSize);
                  }}
                ></Switch>
              )
            }
          }, {
            title: "医院等级",
            align: "center",
            dataIndex: "param",
            render({ hostypeString }) {
              return hostypeString;
            }
          }, {
            title: "医院地址",
            align: "center",
            dataIndex: "param",
            render({ fullAddress }) {
              return fullAddress;
            }
          }, {
            title: "创建时间",
            align: "center",
            dataIndex: "createTime"
          }, {
            title: "操作",
            align: "center",
            fixed: "right",
            render(rows) {
              return (
                <Space>
                  <Button onClick={() => {
                    console.log(rows.id)
                    navigate(`/hospital/show/${rows.id}`)
                  }} type={"primary"}>查看</Button>
                  <Button type={"primary"} onClick={()=>{
                    navigate(`/hospital/department/${rows.hoscode}`)
                  }}>排班</Button>
                </Space>
              )
            }
          }
        ]}
        scroll={{
          x: 1500
        }}
        dataSource={hospitalList}
      ></Table>
    </div>
  );
}

export default HospitalList;